关于context的知识点
context 是react 提供的实现数据共享的api,解决props层层传递的问题
- React.createContext()创建Context对象
- 使用Context Provider包裹组件给他的后代组件提供数据
- Context Provider所有的后代组件,都可以通过Context.Consumer获取到Context数据
useContext(context)
- useContext(context)是针对context(上下文)提出的api
- 它接受React.createContext()的返回结果作为参数也就是context对象 并返回最近的context
- 使用useContext 将不再需要Provider和Consumer
- 当最近的context更新时,那么使用该conntext的hook将会重新渲染
本次用的Hook
例子
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 
 | import React, { useState, createContext } from 'react';
 import ChildA from './components/childA';
 import ChildB from './components/childB';
 
 
 export const InitContext = createContext({
 a: 1
 });
 
 function App() {
 
 const [count, setCount] = useState(1);
 
 return (
 
 <InitContext.Provider
 // value就是通过context 共享的数据 这里是store
 value={{
 count,
 setCount
 }}
 >
 <div className="App" >
 <ChildA />
 <ChildB />
 </div>
 </InitContext.Provider>
 
 );
 }
 
 export default App;
 
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | import React, { useEffect, useContext } from 'react';import { InitContext } from '../../App';
 
 const ChildA = () => {
 const contextData = useContext(InitContext);
 
 return (
 <div>
 {contextData.count}
 </div>
 );
 }
 
 export default ChildA;
 
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | import React, { useState, useContext } from 'react';import { InitContext } from '../../App';
 
 const ChildB = () => {
 const contextData = useContext(InitContext);
 
 
 const add = () => {
 
 contextData.setCount(contextData.count + 1);
 }
 return (
 <button onClick={() => add()}>增加</button>
 );
 }
 
 export default ChildB;
 
 
 
 |